import React ,{ useEffect,useState }from 'react'
import { List,InputItem,Picker,TextareaItem,Toast,Modal } from 'antd-mobile'

import Navbar from '../../components/Navbar'
import ImageWall from './components/ImageWall'
import { reqHousesCondition } from '../../api'
import { getChooseCity } from '../../utils'
import { reqHousePublish } from '../../api'
import './index.scss'

const Item=List.Item
const alert=Modal.alert

const baseImg=[
  '/newImg/7bjk7dcn4.jpg',
  '/newImg/7bjn9i4hl.jpg',
  '/newImg/7bhh89l42.jpg',
  '/newImg/7bkgh93eo.jpg',
  '/newImg/7bk4lcg0n.jpg',
  '/newImg/7bko2ll01.jpg',
  '/newImg/7bk5k3hch.jpg',
  '/newImg/7bkda3lh7.jpg'
]
const baseImgStr=baseImg.join('|')

export default function Publish(props) {

  const {history,location}=props
  const {state}=location

  const chooseCity=getChooseCity()

  const [conditions, setConditions] = useState(null)
  const [visible, setVisible] = useState({type:'roomType',show:false})
  const [isUpdateCommunity, setIsUpdateCommunity] = useState(true)

  const [submitData, setSubmitData] = useState({
    community:{label:'小区名称',data:'',type:'other',render:Community},
    price:{
      label:'租金',
      data:'',
      render:Price,
      arguments:{
        key:'price',
        name:'price',
        type:'number',
        placeholder:'请输入租金/月',
        extra:'￥/月',
      }
    },
    size:{
      label:'建筑面积',
      data:'',
      render:Size,
      arguments:{
        key:'size',
        name:'size',
        type:'number',
        placeholder:'请输入建筑面积',
        extra:'m²',
      }
    },
    roomType:{label:'户型',data:'',type:'other',render:RoomType},
    floor:{label:'所在楼层',data:'',type:'other',render:Floor},
    oriented:{label:'朝向',data:'',type:'other',render:Oriented},
    title:{
      label:'房屋标题',
      data:'',
      type:'title',
      render:HouseTitle,
      arguments:{
        placeholder:'请输入标题（例如：整租 小区名 2室 5000元）',
        rows:2,
      }
    },
    houseImg:{label:'房屋图像',data:baseImgStr,type:'img',render:HouseImg},
    supporting:{label:'房屋配置',data:'',type:'support',render:Supporting},
    description:{
      label:'房屋描述',
      data:'',
      type:'description',
      render:Description,
      arguments:{
        placeholder:'请输入房屋描述的信息',
        rows:5,
      }
    },
  })  

  const cancelSubmit=()=>{
    console.log('cancelSubmit')
    let isNoEmpty=Object.values(submitData).some(i=>i.data!=='')
    if(isNoEmpty){
      alert('提示','是否取消发布房源，退出将清空已填数据',[
        {text:'取消',onPress:()=>null},
        {text:<span style={{color:'#21b97a'}}>确定</span>,onPress:()=>history.replace('/manage')},
      ])
    }else{
      history.replace('/manage')
    }
    
  }

  const submit=()=>{
    let data=Object.entries(submitData).map(i=>([i[0],i[1].data.toString()]))

    if(data.some(i=>i[1]==='')){  //有没有填的信息
      Toast.info('不能为空')
    }else{
      new Promise(async resolve=>{
        let res=await new Promise(async resolve=>{
          let _data=data.reduce((p,c)=>{
            p[c[0]]=c[1]
            return p
          },{})
          let res=await reqHousePublish(_data)
          resolve(res)
        })
        Toast.success(res.description)
        history.replace('/manage')
        resolve()
      })
    }
  }

  useEffect(()=>{
    async function getConditions(params){
      let res=await reqHousesCondition(params)
      setConditions(res.body)
    }
    if(!conditions)getConditions({id:chooseCity.id})
    if(state&&isUpdateCommunity){
      if(state){
        const {data}=state
        const _data=data.reduce((p,c)=>{
          if(c[1]===''){
            p[c[0]]={...submitData[c[0]]}
          }else{
            let obj=submitData[c[0]]
            obj.data=c[1]
            if(c[0]==='community'){
              obj.communityName=c[2]
            }
            p[c[0]]={...obj}
          }
          return p
        },{})
        setSubmitData(_data)
        setIsUpdateCommunity(false)
      }
    }
    
  },[conditions,state,submitData,chooseCity,isUpdateCommunity])

  return (
    <div>
      <div className='publish-navbar'>
        <Navbar title='发布房源'></Navbar>
      </div>
      <div className='publish-content'>
        <List renderHeader={<span className='title'>房源信息</span>}>
          {
            conditions?
            Object.keys(submitData).map(i=>(
              <Item key={i} name={i}>
                {
                  submitData[i].type==='other'?
                  <><span>{submitData[i].label}</span> {submitData[i].render?submitData[i].render({data:conditions,history,visible,setVisible,setSubmitData,submitData}):null}</>:
                  submitData[i].render(submitData,setSubmitData,history)
                }
              </Item>
            )):null
          }
        </List>
      </div>
      <div className='publish-footer'>
        <div onClick={()=>cancelSubmit()}>取消</div>
        <div onClick={()=>submit()}>提交</div>
      </div>
    </div>
  )
}

function Community(props){
  const {history,submitData}=props
  return <div className='am-list-item am-input-item am-list-item-middle other' onClick={()=>history.push('/search',{path:'/publish',data:Object.entries(submitData).map(i=>([i[0],i[1].data.toString()]))})}>
    {
      submitData.community.data===''?
      <span>请输入小区名称<i className='iconfont icon-backRit'></i></span>:
      <span>{submitData.community.communityName}</span>
    }
  </div>
}
function Price(submitData,setSubmitData){
  return <><span>{submitData['price'].label}</span> <InputItem {...submitData['price'].arguments} onChange={val=>setSubmitData({...submitData,price:{...submitData['price'],data:val}})}></InputItem></>
}
function Size(submitData,setSubmitData){
  return <><span>{submitData['size'].label}</span> <InputItem {...submitData['size'].arguments} onChange={val=>setSubmitData({...submitData,size:{...submitData['size'],data:val}})}></InputItem></>
}
function RoomType(params){
  const {visible,setVisible,submitData,data}=params
  return <div className='am-list-item am-input-item am-list-item-middle other' onClick={()=>setVisible({type:'roomType',show:!visible.show})}>
    {
      submitData.roomType.data.length===0?<>请选择 <i className='iconfont icon-backRit'></i></>:
      <span>{data.roomType.find(i=>i.value===submitData.roomType.data).label}</span>
    }
    {
      MyPicker(params)
    }
  </div>
}
function Floor(params){
  const {visible,setVisible,submitData,data}=params
  return <div className='am-list-item am-input-item am-list-item-middle other' onClick={()=>setVisible({type:'floor',show:!visible.show})}>
    {
      submitData.floor.data.length===0?<>请选择 <i className='iconfont icon-backRit'></i></>:
      <span>{data.floor.find(i=>i.value===submitData.floor.data).label}</span>
    }
    {
      MyPicker(params)
    }
  </div>
}
function Oriented(params){
  const {visible,setVisible,submitData,data}=params
  console.log(data)
  return <div className='am-list-item am-input-item am-list-item-middle other' onClick={()=>setVisible({type:'oriented',show:!visible.show})}>
    {
      submitData.oriented.data.length===0?<>请选择 <i className='iconfont icon-backRit'></i></>:
      <span>{data.oriented.find(i=>i.value===submitData.oriented.data).label}</span>
    }
    {
      MyPicker(params)
    }
  </div>
}

function HouseTitle(submitData,setSubmitData){
  return <div className='am-list-content house-title'>
    <span>房屋标题</span>
    <div className='content'>
      <TextareaItem {...submitData.title.arguments} onChange={val=>setSubmitData({...submitData,title:{...submitData['title'],data:val}})}></TextareaItem>
    </div>
  </div>
}
function HouseImg(submitData,setSubmitData){

  return <div className='am-list-content house-title'>
    <span>房屋图像</span>
    <div className='content'>
      <ImageWall {...{submitData,setSubmitData}}></ImageWall>
    </div>
  </div>
}

function Supporting(submitData,setSubmitData){

  const icons={
    "衣柜":'iconfont icon-wardrobe', 
    "洗衣机":'iconfont icon-wash', 
    "空调":'iconfont icon-air', 
    "天然气":'iconfont icon-gas',
    "冰箱":'iconfont icon-ref', 
    "暖气":'iconfont icon-Heat',
    "电视":'iconfont icon-vid', 
    "热水器":'iconfont icon-heater', 
    "宽带":'iconfont icon-broadband',
    "沙发":'iconfont icon-sofa', 
  }
  const data=submitData.supporting.data
  const choose_arr=data.length===0?[]:data.split('|')

  const choose=(item)=>{
    if(choose_arr.includes(item)){//已经选中的，取消选中
      let new_arr=[]
      choose_arr.forEach(i=>{if(i!==item)new_arr.push(i)})
      let data=new_arr.join('|')
      setSubmitData({...submitData,supporting:{...submitData.supporting,data}})
    }else{//没有选中的，直接选中
      setSubmitData({...submitData,supporting:{...submitData.supporting,data:data.length===0?item:data+'|'+item}})
    }
  }

  return <div className='am-list-content house-title'>
    <span>房屋配置</span>
    <div className='content'>
      {
        Object.keys(icons).map(i=><div key={i} className={'icon-item'+(choose_arr.includes(i)?' active':'')} onClick={()=>choose(i)}>
          <i className={icons[i]}></i>
          <span>{i}</span>
        </div>)
      }
    </div>
  </div>
}

function Description(submitData,setSubmitData){

  return <div className='am-list-content house-title'>
    <span>房屋描述</span>
    <div className='content'>
      <TextareaItem {...submitData.description.arguments} onChange={val=>setSubmitData({...submitData,description:{...submitData['description'],data:val}})}></TextareaItem>
    </div>
  </div>
}

function MyPicker({data,visible,submitData,setSubmitData}){
  return <Picker 
      visible={visible.show}
      data={[data[visible.type]]}
      cascade={false}
      onOk={val=>setSubmitData({...submitData,[visible.type]:{...submitData[visible.type],data:val.toString()}})}
    ></Picker>

}